import requests
import argparse
import json
import copy
import urllib3
import re

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


# authorization = "831463f411b498115556f7cc52410c3c"
authorization = "57eb0f34bb053d096eb705070bc26226"
proxy = ""


class GiteeTagUtils:
    def __init__(self, repo: str, owner: str):
        self.repo = repo
        self.owner = owner
        self.headers = {"Authorization": f"token {authorization}", "Content-Type": "application/json"}
        self.proxy = {"https": proxy, "http": proxy}
        self.url = f"https://gitee.com/api/v5/repos/{self.owner}/{self.repo}/tags"

    def add_tag(self, tag_name: str) -> int:
        try:
            data = {
                "refs": "master",
                "tag_name": tag_name,
                "tag_message": f"每日构建生成tag {tag_name}"
            }
            response = requests.post(self.url, json=data, headers=self.headers, verify=False)
            response.raise_for_status()
            print(response.json())
            return 0
        except Exception as e:
            print(f"add tag error: {e}")
            return -1

    def get_tag_list(self, page: int = 1):
        # 根据更新时间倒序，取前五个tag
        params = {
            "sort": "updated",
            "direction": "desc",
            "page": page,
            "per_page": 5
        }
        print(params)
        try:
            response = requests.get(self.url, headers=self.headers, params=params, verify=False)
            response.raise_for_status()
            print(response.json())
            return response.json()
        except Exception as e:
            print(f"add tag error: {e}")

    def get_latest_tag(self, regex=str):
        page = 1
        latest_tag_name = ""
        while page < 10:
            tag_list = self.get_tag_list(page=page)
            tag_name_list = [item['name'] for item in tag_list]
            for tag_name in tag_name_list:
                is_match = re.match(regex, tag_name)
                if is_match:
                    latest_tag_name = tag_name
                    break
            if latest_tag_name:
                break
            page += 1
        return latest_tag_name

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--method", type=str, help="get, add, latest", required=True)
    parser.add_argument("--owner", type=str, help="gitee owner", default="omniai")
    parser.add_argument("--repo", type=str, help="gitee repo", default="omniinfer")
    parser.add_argument("--tag", type=str, help="tag name", default="")
    parser.add_argument("--regex", type=str, help="search latest tag by regex", default="daily_build_")
    
    result, _ = parser.parse_known_args()
    args = copy.deepcopy(result)

    tag_utils = GiteeTagUtils(args.repo, args.owner)
    if args.method == 'add':
        if args.tag:
            retcode = tag_utils.add_tag(args.tag)
            if retcode == 0:
                print("add tag success")
                exit(0)
            else:
                print("add tag fail")
                exit(1)
        else:
            print("add tag, but tag can't be empty")
            exit(1)
    elif args.method == 'get':
        tag_utils.get_tag_list()
        exit(0)
    elif args.method == 'latest':
        latest_tag_name = tag_utils.get_latest_tag(args.regex)
        if latest_tag_name:
            print(latest_tag_name)
            exit(0)
        else:
            print("ERROR: not find regex tag_name in 50 tags")
            exit(-1)
    else:
        print('invalid params: method, allow get or add')
        exit(1)
    